/*
 * Copyright © 2021 Dowsure
 * https://www.dowsure.com/
 *
 * All rights reserved.
 */

package com.dowsure.apisaas.util.smalgorithm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.*;

@Slf4j
public final class FileHelper {

	private static final int BUFFSIZE = 0x10000;

	private FileHelper() {
	}

	public static final void deleteFile(String fileName) {
		if (fileName != null) {
			try {
				File file = new File(fileName);
				if (file.exists()) {
					file.delete();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static final void write(String filePath, byte[] data)
			throws IOException {
		FileOutputStream fos;
		if (filePath == null) {
			throw new IllegalArgumentException("Illegal Argument: filePath");
		}
		if (data == null) {
			throw new IllegalArgumentException("Illegal Argument: data");
		}
		fos = null;
		try {
			fos = new FileOutputStream(filePath);
			fos.write(data, 0, data.length);
			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
				}
			}
		}
	}

	public static final byte[] read(String filePath) throws IOException {
		FileInputStream crls;
		if (filePath == null) {
			throw new IllegalArgumentException("Illegal Argument: filePath");
		}
		crls = null;
		byte[] abyte0;
		try {
			crls = new FileInputStream(filePath);
			byte [] out = new byte[crls.available()];
			byte [] buffer = new byte[BUFFSIZE];
			int rLength;
			for (int offset = 0; (rLength = crls.read(buffer, 0, buffer.length)) != -1; offset += rLength) {
				System.arraycopy(buffer, 0, out, offset, rLength);
			}
			abyte0 = out;
		} catch (IOException e) {
			throw e;
		} finally {
			if (crls != null) {
				try {
					crls.close();
				} catch (Exception e) {
				}
			}
		}
		return abyte0;
	}

	public static final byte[] read(InputStream in) throws IOException {
		if (in == null) {
			throw new IllegalArgumentException("Illegal Argument: in");
		}
		byte []out;
		out = new byte[in.available()];
		byte []buffer = new byte[BUFFSIZE];
		int rLength;
		for (int offset = 0; (rLength = in.read(buffer, 0, buffer.length)) != -1; offset += rLength) {
			System.arraycopy(buffer, 0, out, offset, rLength);
		}
		return out;
	}


	public static final byte[] loadFileBytes(String basePath, String keyName) throws Exception {
		if(StringUtils.isEmpty(basePath)) {
			basePath = FileHelper.class.getClassLoader().getResource("").getPath();
		}
		log.info("basePath is {}", basePath);
		log.info("keyName is {}", keyName);
		return FileHelper.read(basePath + File.separator + keyName);
	}
}
